package com.yiyi.credit.manage.abutment.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class GlobalConfig implements InitializingBean {
    public static final String CONFIG_LOCAL = "local";
    public static final String CONFIG_DEV = "dev";
    public static final String CONFIG_SIT = "sit";
    public static final String CONFIG_ONLINE = "online";
    public static final String PROFILE_NOT_ONLINE = "!online";
    public static final String PROFILE_NOT_ONLINE_HOSTING = "!hosting-prod";
    public static final String CONFIG_ONLINE_HOSTING = "hosting-prod";
    public static final String useProfiledMatch = "matchProfiled";
    private static final Logger logger = LoggerFactory.getLogger(GlobalConfig.class);
    private static final String postfix;

    @Value("${outter.notify.url}")
    private String notifyUrl;

    private static String staticnotifyUrl;

    static {
        String pending = lookupKey("spring.profiles.active");
        if (pending == null || "".equals(pending))
            postfix = CONFIG_LOCAL;
        else
            postfix = pending;
    }

    public static boolean isOnline() {
        return org.apache.commons.lang3.StringUtils.equals(getPostfix(), CONFIG_ONLINE)
                || org.apache.commons.lang3.StringUtils.equals(getPostfix(), CONFIG_ONLINE_HOSTING);
    }

    public static String getNotifyUrl() {
        return staticnotifyUrl;
    }

    public static boolean getBoolean(String key) {
        String val = lookupKey(key);
        try {
            return Boolean.valueOf(key);
        } catch (Exception e) {
            return false;
        }
    }

    public static final String lookupKey(String key) {
        String value = System.getProperty(key, null);
        if (StringUtils.isEmpty(value)) {
            value = System.getenv(key);
        }
        return value;
    }

    public static final String lookupKey(String key, String defaultValue) {
        String value = lookupKey(key);
        return StringUtils.isEmpty(value) ? defaultValue : value;
    }

    public static final String getPostfix() {
        return postfix;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        staticnotifyUrl = notifyUrl;
    }
}